from django.db import models
import uuid
import hashlib
import time

# # Create your models here.
#
# """
# CREATE TABLE `sys_dict_type`  (
#   `dict_id` bigint NOT NULL AUTO_INCREMENT COMMENT '字典主键',
#   `dict_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '字典名称',
#   `dict_type` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '字典类型',
#   `status` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '0' COMMENT '状态（0正常 1停用）',
#   `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '创建者',
#   `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
#   `update_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '更新者',
#   `update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
#   `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注',
#   PRIMARY KEY (`dict_id`) USING BTREE,
#   UNIQUE INDEX `dict_type`(`dict_type`) USING BTREE
# ) ENGINE = InnoDB AUTO_INCREMENT = 171 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '字典类型表' ROW_FORMAT = Dynamic;
# """
#
#
# class SysDictType(models.Model):
#     dict_id = models.AutoField(primary_key=True)
#     dict_name = models.CharField(max_length=128, verbose_name='字典名称', db_index=True)
#     dict_type = models.CharField(max_length=128, verbose_name='字典类型', db_index=True)
#     is_delete = models.BooleanField(default=False, verbose_name="是否逻辑删除", help_text="是否逻辑删除 0正常 1停用")
#     create_by = models.CharField(max_length=128, verbose_name='创建者')
#     create_time = models.DateTimeField(verbose_name='发布日期', auto_now_add=True, null=True)
#     update_by = models.CharField(max_length=128, verbose_name='更新者')
#     update_time = models.DateTimeField(verbose_name='最后修改日期', auto_now=True, null=True)
#     remark = models.CharField(max_length=512, verbose_name='备注')
#
#     class Meta:
#         db_table = 'sys_dict_type'
#         verbose_name = '字典类型表'
#
#     def __str__(self):
#         return f"{self.Meta.db_table}__{self.code}"
#
#
# """
# CREATE TABLE `sys_dict_data`  (
#   `dict_code` bigint NOT NULL AUTO_INCREMENT COMMENT '字典编码',
#   `dict_sort` int NULL DEFAULT 0 COMMENT '字典排序',
#   `dict_label` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '字典标签',
#   `dict_value` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '字典键值',
#   `dict_type` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '字典类型',
#   `css_class` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '样式属性（其他样式扩展）',
#   `list_class` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '表格回显样式',
#   `is_default` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否默认（Y是 N否）',
#   `status` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '0' COMMENT '状态（0正常 1停用）',
#   `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '创建者',
#   `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
#   `update_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '更新者',
#   `update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
#   `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注',
#   PRIMARY KEY (`dict_code`) USING BTREE
# ) ENGINE = InnoDB AUTO_INCREMENT = 1936 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '字典数据表' ROW_FORMAT = Dynamic;
# """
#
#
# class SysDictData(models.Model):
#     dict_code = models.AutoField(primary_key=True, verbose_name="字典编码")
#     dict_sort = models.IntegerField(default=0, verbose_name='字典排序', null=False)
#     dict_label = models.CharField(max_length=128, verbose_name='字典标签')
#     dict_value = models.CharField(max_length=128, verbose_name='字典键值')
#     dict_type = models.CharField(max_length=128, verbose_name='字典类型', db_index=True)
#     css_class = models.CharField(max_length=128, verbose_name='样式属性（其他样式扩展）', null=True)
#     list_class = models.CharField(max_length=128, verbose_name='表格回显样式', null=True)
#     is_default = models.CharField(max_length=16, default="Y", verbose_name="是否默认", help_text="是否默认（Y是 N否）")
#     is_delete = models.BooleanField(default=False, verbose_name="是否逻辑删除", help_text="是否逻辑删除 0正常 1停用")
#     create_by = models.CharField(max_length=128, verbose_name='创建者', null=True)
#     create_time = models.DateTimeField(verbose_name='发布日期', auto_now_add=True, null=True)
#     update_by = models.CharField(max_length=128, verbose_name='更新者')
#     update_time = models.DateTimeField(verbose_name='最后修改日期', auto_now=True, null=True)
#     remark = models.CharField(max_length=512, verbose_name='备注',null=True)
#
#     class Meta:
#         db_table = 'sys_dict_data'
#         verbose_name = '字典数据表'
#         constraints = [
#             models.UniqueConstraint(fields=['dict_type', 'dict_sort'], name='unique_dict_type_dict_sort_index')
#         ]
#
#     def __str__(self):
#         return f"{self.Meta.db_table}__{self.code}"

class AppSecret(models.Model):
    """
    应用秘钥管理表
    用于存储app_id和app_secret的对应关系
    """
    id = models.AutoField(primary_key=True, verbose_name="主键ID")
    app_id = models.CharField(max_length=64, unique=True, verbose_name="应用ID", help_text="业务应用唯一标识", db_index=True)
    app_secret = models.CharField(max_length=128, verbose_name="应用秘钥", help_text="业务应用秘钥")
    app_name = models.CharField(max_length=128, verbose_name="应用名称", help_text="业务应用名称")
    status = models.BooleanField(default=True, verbose_name="状态", help_text="是否启用 1启用 0禁用", db_index=True)
    is_delete = models.BooleanField(default=False, verbose_name="是否删除", help_text="是否逻辑删除", db_index=True)
    create_by = models.CharField(max_length=128, verbose_name='创建者', null=True, blank=True)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True, db_index=True)
    update_by = models.CharField(max_length=128, verbose_name='更新者', null=True, blank=True)
    update_time = models.DateTimeField(verbose_name='更新时间', auto_now=True)
    remark = models.CharField(max_length=512, verbose_name='备注', null=True, blank=True)

    class Meta:
        db_table = 'app_secret'
        verbose_name = '应用秘钥表'
        verbose_name_plural = '应用秘钥表'

    def __str__(self):
        return f"{self.app_name}({self.app_id})"

    @classmethod
    def generate_app_secret(cls):
        """
        生成应用秘钥
        """
        # 使用时间戳和随机UUID生成秘钥
        timestamp = str(int(time.time()))
        random_uuid = str(uuid.uuid4())
        secret_string = f"{timestamp}_{random_uuid}"
        return hashlib.sha256(secret_string.encode()).hexdigest()[:32]

    @classmethod
    def generate_app_id(cls):
        """
        生成应用ID
        """
        # 使用时间戳和随机UUID生成应用ID
        timestamp = str(int(time.time()))
        random_uuid = str(uuid.uuid4())
        app_id_string = f"{timestamp}_{random_uuid}"
        return hashlib.md5(app_id_string.encode()).hexdigest()[:16]
